<?php
/**
 * +--------------------------------------------------------+
 * @Created by PhpStorm.
 * @Category SocketService.php
 * @Depiction:
 * Author: hwy
 * Date: 2021/2/3  10:00
 * +--------------------------------------------------------+
 */

namespace App\Services;

use App\Exceptions\ResponseException;
use App\Models\StockData;
use App\Models\StockList;
use App\Models\StockPea;
use Carbon\Carbon;
use App\Models\Stock;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class StockService extends BaseService
{
    protected $stock;

    public function __construct()
    {
        $this->stock = new Stock();
    }

    /**
     * @param $param
     * @return mixed
     * @Depiction 获取某一条记录
     * @Author hwy
     * @Date  2021/2/3  11:22
     */
    public function getOne($param)
    {
        return $this->stock::find($param);
    }

    /**
     * @param $params 参数
     * @return mixed
     * @Depiction 获取分页数据
     * @Author hwy
     * @Date  2020/5/18  18:05
     */
    public function getList($params)
    {
        $query   = $this->stock->query();
        $perPage = $this->perPage($params);
        $query   = $this->paramsSet($params, $query);
        $query->orderBy('warm', 'asc');
        $query->orderBy('attention', 'asc');
        $query->orderBy('id', 'desc');
        $list = $query->paginate($perPage)->toArray();

        return return_success_msg(ResponseException::REQUEST_SUCCESS_MESSAGE, $list);
    }

    /**
     * @param int $type 1:获取数据，并更新缓存  2:直接获取缓存数据
     * @return mixed
     * @Depiction
     * @Author hwy
     * @Date 2021/4/29  11:43
     */
    public function getAll($type = 1)
    {
        if ($type == 1) {
            $data = $this->stock->orderBy('warm', 'asc')->orderBy('attention', 'asc')->orderBy('id', 'desc')->get()->pluck('name', 'code');
            Cache::put('stock_list', $data);
        } else {
            $data = Cache::has('stock_list') ? Cache::get('stock_list') : $this->getAll();
        }

        return $data;
    }

    /**
     * @param $params
     * @param $get_url
     * @return array
     * @Depiction
     * @Author hwy
     * @Date 2021/5/27  16:14
     */
    public function addData($params, $get_url)
    {
        $stock        = explode('/', $params->stock);
        $data['name'] = $stock[0];
        $data['code'] = $stock[1];

        $check = $this->stock->query()->where('code', $data['code'])->count();
        if ($check > 0) {
            return return_error_msg($data['name'] . '已存在');
        }

        $datas            = $this->get_stock_real_time([$data['code'] => $data['name']], $get_url);
        $new_data         = $datas[0];
        $data['cost']     = $new_data[3];
        $data['add_cost'] = $new_data[3];

        try {
            $add = $this->stock->create($data);
            if ($add) {
                $list = $this->getAll();
            }
        } catch (\Exception $e) {
            return return_error_msg($e->getMessage());
        }

        if ($add) {
            return return_success_msg(ResponseException::SUCCESS_ADD_MESSAGE);
        } else {
            return return_error_msg(ResponseException::ERROR_ADD_MESSAGE);
        }
    }

    /**
     * @param $params
     * @param $id
     * @return array
     * @Depiction
     * @Author hwy
     * @Date 2021/5/27  16:14
     */
    public function editData($params, $id)
    {
        $data = $this->getOne($id);
        if (empty($data)) {
            return ['code' => -1, 'message' => '数据不存在！'];
        }
        $data->name         = $params->name;
        $data->code         = $params->code;
        $data->expect_low   = $params->expect_low;
        $data->expect_hight = $params->expect_hight;

        try {
            $edit = $data->save();
        } catch (\Exception $e) {
            return return_error_msg($e->getMessage());
        }

        if ($edit) {
            $list = $this->getAll();
            Cache::put('stock_list', $list);

            return return_success_msg(ResponseException::SUCCESS_EDIT_MESSAGE);
        } else {
            return return_error_msg(ResponseException::ERROR_EDIT_MESSAGE);
        }
    }

    /**
     * @param $ids
     * @return array
     * @Depiction
     * @Author hwy
     * @Date 2021/5/27  16:14
     */
    public function delData($ids)
    {
        $del = $this->commomDel($this->stock, $ids);
        return $del;
    }

    /**
     * @param $request
     * @param $get_url
     * @return array
     * @Depiction
     * @Author hwy
     * @Date 2021/5/27  16:14
     */
    public function setCost($request, $get_url)
    {

        $stock_list = $this->getAll(2);

        $new_data = $this->get_stock_real_time($stock_list, $get_url);

        $stocks = [];
        $time   = Carbon::now()->toDateTimeString();
        foreach ($new_data as $val) {
            $stock['code'] = $val[2];
            if (empty($request->type)) {
                $stock['cost']       = $val[3];
                $stock['updated_at'] = $time;
            } else {
                $stock['add_cost']   = $val[3];
                $stock['created_at'] = $time;
            }
            $stocks[] = $stock;
        }

        $this->updateBatch($stocks, config('database.connections.mysql.prefix') . 'stock');

        return return_success_msg(ResponseException::SUCCESS_EDIT_MESSAGE);
    }

    /**
     * @param $id
     * @return array
     * @Depiction
     * @Author hwy
     * @Date 2021/5/27  16:14
     */
    public function setAttention($id)
    {
        $data            = $this->getOne($id);
        $data->attention = $data->attention == 1 ? 2 : 1;

        try {
            $edit = $data->save();
        } catch (\Exception $e) {
            return return_error_msg($e->getMessage());
        }

        if ($edit) {
            $list = $this->getAll();

            return return_success_msg(ResponseException::SUCCESS_EDIT_MESSAGE);
        } else {
            return return_error_msg(ResponseException::ERROR_EDIT_MESSAGE);
        }
    }

    /**
     * @param $id
     * @return array
     * @Depiction
     * @Author hwy
     * @Date 2021/5/27  16:14
     */
    public function setWarm($id)
    {
        $data       = $this->getOne($id);
        $data->warm = $data->warm == 1 ? 2 : 1;

        try {
            $edit = $data->save();
        } catch (\Exception $e) {
            return return_error_msg($e->getMessage());
        }

        if ($edit) {
            $list = $this->getAll();

            return return_success_msg(ResponseException::SUCCESS_EDIT_MESSAGE);
        } else {
            return return_error_msg(ResponseException::ERROR_EDIT_MESSAGE);
        }
    }

    /**
     * @param $id
     * @return array
     * @Depiction 从亿牛网重置历史数据
     * @Author hwy
     * @Date 2021/5/27  16:15
     */
    public function isInit($id)
    {
        $data      = $this->getOne($id);
        $init_data = $this->stockYnData(2, $data->code);

        try {
            DB::beginTransaction();
            $data->is_init = 1;
            $edit          = $data->save();
            if (!$edit) {
                DB::rollBack();
            } else {
                $add = StockPea::query()->insert($init_data);
            }
        } catch (\Exception $e) {
            DB::rollBack();
            return return_error_msg($e->getMessage());
        }

        if ($add) {
            DB::commit();
            return return_success_msg(ResponseException::SUCCESS_EDIT_MESSAGE);
        } else {
            DB::rollBack();
            return return_error_msg(ResponseException::ERROR_EDIT_MESSAGE);
        }
    }


    /**
     * @return array
     * @Depiction 获取指数
     * @Author hwy
     * @Date 2021/4/12  10:37
     */
    public function getStockNum()
    {
        $url  = 'http://hq.sinajs.cn/list=s_sh000001';
        $data = curl($url);
        $data = iconv("gb2312", "utf-8//IGNORE", $data);
        $data = explode(',', $data);
        array_pop($data);
        $res_data = [
            'zs'  => $data[1],
            'per' => $data[3],
            'zd'  => $data[2],
        ];

        return $res_data;
    }

    /**
     * @param $stock_list
     * @param $get_url
     * @return mixed
     * @Depiction 查询实时数据情况
     * @Author hwy
     * @Date  2021/2/18  17:38
     */
    public function get_stock_real_time($stock_list, $get_url)
    {
        $data_list = $this->toolStockSourceData($stock_list, $get_url, ['sz', 'sh']);

        $return_data = [];
        foreach ($data_list as $key => $val) {
            if (!empty($val)) {
                $return_data[$key] = explode('~', $val);
            }
        }

        return $return_data;
    }

    /**
     * @param $stock_list
     * @param $get_url
     * @return mixed
     * @Depiction 查询资金情况
     * @Author hwy
     * @Date  2021/2/18  17:38
     */
    public function get_stock_real_time_cap($stock_list, $get_url)
    {
        $data_list_cap = $this->toolStockSourceData($stock_list, $get_url, ['ff_sz', 'ff_sh']);

        $return_data = [];
        foreach ($data_list_cap as $k => $v) {//002463
            if (!empty($v)) {
                $cf_data                   = explode('~', $v);
                $return_data[$k]['num']    = substr(trim($cf_data[0]), 7, 6);
                $return_data[$k]['zllr']   = $cf_data[1];
                $return_data[$k]['zllc']   = $cf_data[2];
                $return_data[$k]['zljlr']  = $cf_data[3];
                $return_data[$k]['zljlr3'] = $cf_data[4];
                $return_data[$k]['shlr']   = $cf_data[5];
                $return_data[$k]['shlc']   = $cf_data[6];
                $return_data[$k]['shjlr']  = $cf_data[7];
                $return_data[$k]['shjlr3'] = $cf_data[8];
                $return_data[$k]['zjlrzh'] = $cf_data[9];
            }
        }

        return $return_data;
    }

    /**
     * @param $stock_list
     * @param $get_url
     * @return array
     * @Depiction 查询盘口数据
     * @Author hwy
     * @Date 2021/4/12  10:38
     */
    public function get_stock_real_time_pksh($stock_list, $get_url)
    {
        $data_list_pksh = $this->toolStockSourceData($stock_list, $get_url, ['s_pksz', 's_pksh']);

        $return_data = [];
        foreach ($data_list_pksh as $k => $v) {//002463
            if (!empty($v)) {
                $cf_data                = trim($v);
                $cf_data                = str_replace('v_s_pksz', '', $cf_data);
                $cf_data                = str_replace('v_s_pksh', '', $cf_data);
                $cf_data                = str_replace('="', '~', $cf_data);
                $cf_data                = str_replace('"', '', $cf_data);
                $cf_data                = explode('~', $cf_data);
                $return_data[$k]['num'] = $cf_data[0];
                $return_data[$k][1]     = $cf_data[1];
                $return_data[$k][2]     = $cf_data[2];
                $return_data[$k][3]     = $cf_data[3];
                $return_data[$k][4]     = $cf_data[4];
            }
        }

        return $return_data;
    }

    /**
     * @return false
     * @Depiction 定时获取数据
     * @Author hwy
     * @Date 2021/4/29  11:32
     */
    public function monitorCapStock()
    {
        $now = Carbon::now();
        if ($now->isWeekday() == false) {
            return false;
        }

        $y  = $now->year;//
        $m  = $now->month;//
        $d  = $now->day;//
        $h  = $now->hour;//
        $mi = $now->minute;//
        if ($h == 9 && $mi == 20) {  //9    10
            //清空缓存
            Cache::flush();
        }

        if ($h < 12) {
            $first  = Carbon::create($y, $m, $d, 9, 25);
            $second = Carbon::create($y, $m, $d, 11, 31);
            if (!$now->between($first, $second)) {
                return false;
            }
        } else {
            $first  = Carbon::create($y, $m, $d, 13);//13
            $second = Carbon::create($y, $m, $d, 15, 1);//15
            if (!$now->between($first, $second)) {
                return false;
            }
        }

        $get_url = config('other.stock_url');

        $stock_list = $this->getAll(2);

        $data_zj   = $this->get_stock_real_time($stock_list, $get_url);
        $data_cap  = $this->get_stock_real_time_cap($stock_list, $get_url);
        $data_pksh = $this->get_stock_real_time_pksh($stock_list, $get_url);

        //stock_zj_  价格数据
        //stock_cjl_  成交量数据
        //stock_cost_  资金数据
        //stock_pk_  盘口数据
        if ($data_zj && $data_cap && $data_pksh) {
            $t = $now->toDateTimeString();
            //股票数据
            foreach ($data_zj as $val) {
                //数值变动
                $cache_name_stock = 'stock_jg_' . $val[2];
                if (Cache::has($cache_name_stock)) {
                    $stock_zj = Cache::get($cache_name_stock);
                    $stock_zj = array_merge($stock_zj, [[$t, $val[3]]]);
                } else {
                    $stock_zj = [];
                    $stock_zj = array_merge($stock_zj, [[$t, $val[3]]]);
                }
                Cache::put($cache_name_stock, $stock_zj, 60 * 60 * 12);

                //成交量
                $cache_name_stock_cjl = 'stock_cjl_' . $val[2];
                if (Cache::has($cache_name_stock_cjl)) {
                    $stock_cjl = Cache::get($cache_name_stock_cjl);
                    $stock_cjl = array_merge($stock_cjl, [[$t, $val[6]]]);
                } else {
                    $stock_cjl = [];
                    $stock_cjl = array_merge($stock_cjl, [[$t, $val[6]]]);
                }
                Cache::put($cache_name_stock_cjl, $stock_cjl, 60 * 60 * 12);
            }

            //资金数据
            foreach ($data_cap as $val) {
                //资金
                $cache_name = 'stock_zlzj_' . $val['num'];
                if (Cache::has($cache_name)) {
                    $stock_cost = Cache::get($cache_name);
                    $stock_cost = array_merge($stock_cost, [[$t, $val['zljlr']]]);
                } else {
                    $stock_cost = [];
                    $stock_cost = array_merge($stock_cost, [[$t, $val['zljlr']]]);
                }

                Cache::put($cache_name, $stock_cost, 60 * 60 * 12);
            }

            //盘口
            foreach ($data_pksh as $val) {
                //数值变动
                $cache_name_pksh = 'stock_pk_' . $val['num'];
                unset($val['num']);
                if (Cache::has($cache_name_pksh)) {
                    $stock_pksh = Cache::get($cache_name_pksh);
                    $stock_pksh = array_merge($stock_pksh, [[$t, $val]]);
                } else {
                    $stock_pksh = [];
                    $stock_pksh = array_merge($stock_pksh, [[$t, $val]]);
                }
                Cache::put($cache_name_pksh, $stock_pksh, 60 * 60 * 12);
            }
        }
    }

    /**
     * @param $num
     * @param $time
     * @return array|\string[][]
     * @Depiction 图表数据 - 价格
     * @Author hwy
     * @Date 2021/4/29  11:31
     */
    public function jgDataHandle($num, $time)
    {
        $data        = Cache::get('stock_jg_' . $num);
        $retuen_data = [];
        if (!empty($data)) {
            foreach ($data as $val) {
                if (Carbon::parse($val[0])->gt($time)) {
                    $retuen_data[] = $val;
                }
            }
        }
        return $retuen_data;
    }

    /**
     * @param $num
     * @param $time
     * @return array|\string[][]
     * @Depiction 图表数据 - 主力资金
     * @Author hwy
     * @Date 2021/4/29  11:24
     */
    public function zlzjDataHandle($num, $time)
    {
        $data        = Cache::get('stock_zlzj_' . $num);
        $retuen_data = [];
        if (!empty($data)) {
            foreach ($data as $val) {
                if (Carbon::parse($val[0])->gt($time)) {
                    $retuen_data[] = $val;
                }
            }
        }

        return $retuen_data;
    }

    /**
     * @param $num
     * @param $time
     * @return array
     * @Depiction 图表数据 - 盘口
     * @Author hwy
     * @Date 2021/4/29  11:30
     */
    public function pkDataHandle($num, $time)
    {
        $data = Cache::get('stock_pk_' . $num);

        $retuen_data_one = [];
        if (!empty($data)) {
            $nums                 = count($data);
            $retuen_data_ones     = @$data[$nums - 1];
            $retuen_data_one[0]   = $retuen_data_ones[0];
            $retuen_data_one[1][] = $retuen_data_ones[1][1];
            $retuen_data_one[1][] = $retuen_data_ones[1][2];
            $retuen_data_one[1][] = $retuen_data_ones[1][3];
            $retuen_data_one[1][] = $retuen_data_ones[1][4];
        }
        if (empty($retuen_data_one)) {
            $retuen_data_one = ['2020-10-14 14:24:00', [0.25, 0.25, 0.25, 0.25]];
        }

        $retuen_data = [];
        if (!empty($data)) {
            foreach ($data as $val) {
                if (Carbon::parse($val[0])->gt($time)) {
                    $retuen_data[] = $val;
                }
            }
        }


        $return = [
            'retuen_data_one' => $retuen_data_one,
            'retuen_data'     => $retuen_data,
        ];
        return $return;
    }

    /**
     * @param $num
     * @param $time
     * @return array
     * @Depiction 图表数据 - 成交量
     * @Author hwy
     * @Date 2021/4/29  11:30
     */
    public function cjlDataHandle($num, $time)
    {
        $data        = Cache::get('stock_cjl_' . $num);
        $retuen_data = [];
        if (!empty($data)) {
            foreach ($data as $val) {
                if (Carbon::parse($val[0])->gt($time)) {
                    $retuen_data[] = $val;
                }
            }
        }

        return $retuen_data;
    }

    /**
     * @Depiction 先做数据永久性存储
     * @Author hwy
     * @Date  2020/10/20  17:28
     */
    public function stock_data_clean()
    {
        $stock_list = $this->getAll(2);
        $list       = [];
        $type       = [1, 2, 3, 4];//1:价格  2主力资金  3盘口  4成交量
        $time       = Carbon::now();
        if ($time->isWeekday() == false) {
            return false;
        }
        $time = $time->toDateTimeString();

        foreach ($stock_list as $key => $val) {
            foreach ($type as $v1) {
                $data['name'] = $val;
                $data['code'] = $key;
                $data['type'] = $v1;
                if ($v1 === 1) {
                    $cache_name = 'stock_jg_' . $key;
                } elseif ($v1 === 2) {
                    $cache_name = 'stock_zlzj_' . $key;
                } elseif ($v1 === 3) {
                    $cache_name = 'stock_pk_' . $key;
                } elseif ($v1 === 1) {
                    $cache_name = 'stock_cjl_' . $key;
                }
                $data['value']      = json_encode(Cache::get($cache_name));
                $data['created_at'] = $data['updated_at'] = $time;

                $list[] = $data;
            }
        }

        StockData::addData($list);

        return true;
    }

    /**
     * @param $stock_list
     * @param $get_url
     * @param $pre
     * @return false|string[]
     * @Depiction 统一方法 - 获取源数据
     * @Author hwy
     * @Date 2021/4/29  11:37
     */
    public function toolStockSourceData($stock_list, $get_url, $pre)
    {
        $list = ''; //查询列表
        foreach ($stock_list as $key => $value) {
            if (substr($key, 0, 1) == 0) {
                $cap_pre = $pre[0];
            } else {
                $cap_pre = $pre[1];
            }
            $list = $list . ',' . $cap_pre . $key;
        }

        $list      = ltrim($list, ",");
        $stock_url = $get_url . $list;

        $stock_data = curl($stock_url);
        $stock_data = iconv("gb2312", "utf-8//IGNORE", $stock_data);
        $stock_data = explode(';', $stock_data);
        array_pop($stock_data);

        return $stock_data;
    }

    /**
     * @param int $type
     * @param string $key
     * @param int $t
     * @return array
     * @Depiction 数据
     * @Author hwy
     * @Date 2021/5/27  16:16
     */
    public function stockYnData(int $type = 2, string $key = '002384', int $t = 120)
    {
        $fund_code = $key;
        if (substr($key, 0, 1) == 0) {
            $keys = 'sz' . $key;
        } else {
            $keys = 'sh' . $key;
        }
        $stockYnData = [];
        switch ($type) {
            case 1:
                // https://eniu.com/static/data/stock_list.json
                $stock_list_url = 'https://eniu.com/static/data/stock_list.json';
                $stock_list     = curl($stock_list_url);
                $stock_list     = json_decode($stock_list, true);

                $delete = StockList::query()->truncate();//截断表
                $add    = StockList::query()->insert($stock_list);

                return return_success_msg(ResponseException::SUCCESS_EDIT_MESSAGE);
                break;
            case 2:
                // 市盈率 per
                // 参数：3/6/12/60/120/all
                // $pea_url = 'https://eniu.com/chart/pea/sh600584/t/60';
                $pea_url     = 'https://eniu.com/chart/pea/' . $keys . '/t/' . $t;
                $yn_pea_data = curl($pea_url);
                $yn_pea_data = json_decode($yn_pea_data, true);

                $date   = array_unique($yn_pea_data['date']);
                $price  = $this->toolInitYnData($yn_pea_data, 'price');
                $pe_ttm = $this->toolInitYnData($yn_pea_data, 'pe_ttm');

                // 市净率 pea
                // 参数：3/6/12/60/120/all
                // $pba_url = 'https://eniu.com/chart/pba/sh600584/t/60';
                $pba_url     = 'https://eniu.com/chart/pba/' . $keys . '/t/' . $t;
                $yn_pba_data = curl($pba_url);
                $yn_pba_data = json_decode($yn_pba_data, true);
                $pb          = $this->toolInitYnData($yn_pba_data, 'pb');

                // 股息率 dva
                // 参数：3/6/12/60/120/all
                // $dva_url = https://eniu.com/chart/dva/sh601318/t/12
                $dva_url     = 'https://eniu.com/chart/dva/' . $keys . '/t/' . $t;
                $yn_dva_data = curl($dva_url);
                $yn_dva_data = json_decode($yn_dva_data, true);
                $dv          = $this->toolInitYnData($yn_dva_data, 'dv');

                foreach ($date as $k => $value) {

                    $stockYnData[$value]['stock_id'] = $key;
                    $stockYnData[$value]['date']     = $value;
                    $stockYnData[$value]['price']    = $price[$value] ?? 0;
                    $stockYnData[$value]['pe']       = $pe_ttm[$value] ?? 0;
                    $stockYnData[$value]['pb']       = $pb[$value] ?? 0;
                    $stockYnData[$value]['dv']       = $dv[$value] ?? 0;

                }

                return $stockYnData;
                break;

            case 3:
                $fund_url  = 'https://eniu.com/fundDetailCharts/' . $fund_code . '/c/' . $t;
                $fund_data = curl($fund_url);
                $fund_data = json_decode($fund_data, true);
                $fundData  = $this->toolInitYnData($fund_data, 'dwjz', 'jzrq');
                return $fundData;
                break;
            default:
                dd('error');
                break;

        }
        // 列表

    }

    public function toolInitYnData($data, $ele, $keys = 'date')
    {
        foreach ($data[$keys] as $k => $val) {
            $res_data[$val] = $data[$ele][$k];
        }

        return $res_data;
    }

    /**
     * @return array
     * @Depiction 获取数据池 所有数据
     * @Author hwy
     * @Date 2021/5/27  16:16
     */
    public function getStockAll()
    {

        $data = Cache::remember('getStockAllList', $cache_ttl = Carbon::now()->addDay(), function () {
            return $data = StockList::query()->get();
        });

        // foreach ($data as $key => $val){
        //     $list[$key] = $val->stock_name . '/' . $val->stock_name;
        // }

        return return_success_msg(ResponseException::REQUEST_SUCCESS_MESSAGE, $data);
    }

    /**
     * @param $key
     * @return mixed
     * @Depiction
     * @Author hwy
     * @Date 2021/5/27  16:17
     */
    public function getPeData($key)
    {
        Cache::pull('getPeData_' . $key);
        $data = Cache::remember('getPeData_' . $key, $cache_ttl = Carbon::now()->addHours(1), function () use ($key) {
            return StockPea::query()->select('id', 'pe', 'pb', 'dv', 'price', 'date')
                ->where('date', '>', Carbon::now()->subDays(400))
                ->where('stock_id', $key)->get();
        });

        return $data;
    }

    public function addPeDataReal()
    {
        $stock_data = $this->stock->query()->select('code', 'name')->where('is_init', 1)->get()->pluck('name', 'code')->toArray();

        $data = $this->get_stock_real_time($stock_data, config('other.stock_url'));

        $today       = Carbon::today()->toDateTimeString();
        $insertDatas = [];
        foreach ($data as $val) {
            $insertData['stock_id'] = $val[2];
            $insertData['date']     = $today;
            $insertData['price']    = $val[3] ?? 0;
            $insertData['pe']       = $val[39] ?? 0;
            $insertData['pb']       = $val[46] ?? 0;
            $insertData['dv']       = $val[64] ?? 0;

            $insertDatas[] = $insertData;
        }

        $add = StockPea::query()->insert($insertDatas);

        return true;
    }

    public function getXueqiuData()
    {
        $url = 'https://xueqiu.com/query/v1/symbol/search/status?u=4350615231&uuid=1399990773553983488&count=20&comment=0&symbol=SH605189&hl=0&source=all&sort=&page=2&q=&type=11&session_token=null&access_token=73886016e50515a01616129f93ccaa3b8d003eb3';

        $data = curl($url);
        $data = json_decode($data, true);
        dd($data);
    }

    public function fundLoopBack($fund_data, $date_n = '', $val = 4, $cost = 300)
    {
        //选个时间定投

        $res_data = [];
        // $val      = 4;
        $num   = 0;
        $d_num = 0;
        // $date_n   = Carbon::now()->subDays($days)->toDateString();

        $date      = Carbon::parse($date_n)->addDay()->toDateString();
        $date      = $this->toolCheckDate($fund_data, $date);
        $s_date    = $date;
        $fene      = 0;
        $hf_acount = 0;
        for ($i = 0; $i < $val; $i++) {

            $date       = $this->toolCheckDate($fund_data, $date);
            $dates[]    = $date;

            $tj = 0;
            $sy = 0;
            // if($hf_acount != 0){
            //     $fund_datas_i = trim($fund_data[$date]);
            //     $sy = (($fene * $fund_datas_i) - $hf_acount);
            //     $tj =  $sy / $hf_acount;
            //
            //     if ($tj < -0.1) {
            //         $cost = 200;
            //     }elseif ($tj > 0.1) {
            //         $cost = 50;
            //     }else{
            //         $cost = 100;
            //     }
            // }
            $s_date = Carbon::parse($date)->subDays(7)->toDateString();
            $s_date = $this->toolCheckDate($fund_data, $s_date);
            $fund_datas_i_s = trim($fund_data[$s_date]);

            $e_date = $this->toolCheckDate($fund_data, $date);
            $fund_datas_i_e = trim($fund_data[$e_date]);
            $up = ($fund_datas_i_e-$fund_datas_i_s)/$fund_datas_i_s;

            if ($up < -0.04 && -0.09 < $up) {
                $cost = 200;
            } elseif ($up > 0.04) {
                $cost = 50;
            }  elseif (-0.09 > $up) {
                $cost = 500;
            } else {
                $cost = 100;
            }



            $fund_datas = trim($fund_data[$e_date]);
            $fene       += $cost / $fund_datas;
            $hf_acount  += $cost;

            dump('第' . $i . '周：定投' . $cost . '，涨幅：' . $up);
            // dump('第' . $i . '周：定投' . $cost . '，收益率：' . $tj . '，收益：' . $sy);
            //end
            $date = Carbon::parse($date)->addDays(7)->toDateString();
        }

        $date = $this->toolCheckDate($fund_data, $date);
        //一周后 卖出
        $fund_datas = trim($fund_data[$date]);
        $acount     = $fene * $fund_datas;
        $res        = $acount - $hf_acount;
        if ($res > 0) {
            $num += 1;
        } else {
            $d_num += 1;
        }
        $res_datas['time']     = $s_date . '--' . $date;
        $res_datas['week_num'] = $val;
        $res_datas['week']     = $this->toolGetWeek($s_date);
        $res_datas['sy']       = $res;
        $res_datas['hf']       = $hf_acount;
        $res_datas['syl']      = $res / $hf_acount;

        $res_data[] = $res_datas;

        // $this->toolInitWeek($res_data);

        $return_data['data'] = $res_data[0];
        $return_data['z']    = $num;
        $return_data['k']    = $d_num;


        return $return_data;

    }

    private function toolCheckDate($fund_data, $date)
    {
        for ($d = 1; $d < 100; $d++) {
            if (!array_key_exists($date, $fund_data)) {
                $date = Carbon::parse($date)->addDay()->toDateString();
            } else {
                break;
            }
        }

        return $date;
    }

    private function toolGetWeek($date)
    {
        $weekarray = ["日", "一", "二", "三", "四", "五", "六"];

        return date("w", strtotime($date));
    }

    private function toolInitWeek($res_data, $type = 1)
    {
        $week = [0, 1, 2, 3, 4, 5, 6];
        foreach ($week as $val) {
            foreach ($res_data as $value) {
                if ($value['week'] == $val) {
                    $data[$val][] = $value;
                }
            }
        }
        $all_init = 0;
        foreach ($data as $key => $val1) {
            $all_init = 0;
            $per      = count($val1);
            foreach ($val1 as $key1 => $val2) {
                $all_init += $val2['sy'];
            }
            dump('星期' . $key . '：' . $all_init . '/' . $per . '=' . $all_init / $per);
        }


        dd('end');
    }

}
